#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project : aimix
@File    : ai_mix_worker.py
@IDE     : PyCharm
@Author  : admin
@Date    : 2025/4/30 12:12
"""
import os
import json
import traceback
import tempfile
from PyQt5.QtCore import QThread, pyqtSignal
from utils.tools import request
from utils.load_file import load_files
from config import Config


class AiMixSynthesisWorker(QThread):
    """Ai智能剪辑"""
    result = pyqtSignal(str)
    failed = pyqtSignal(Exception)

    def __init__(self, file_path, count, output_folder, subtitle, voice, headers, parent=None):
        super(AiMixSynthesisWorker, self).__init__()
        self.headers = headers
        self.file_path = file_path
        self.count = count
        self.output_folder = output_folder
        self.subtitle = subtitle
        self.voice = voice


    def generate_files_data(self):
        """
        生成文件上传所需的 files 参数
        :param file_paths: 文件路径列表
        :return: files 参数
        """
        files = []
        file_type_mapping = {
            '.mp4': 'video/mp4',
            '.mov': 'video/quicktime',
            '.avi': 'video/x-msvideo',
            '.mkv': 'video/x-matroska',
            '.mp3': 'audio/mpeg',
            '.wav': 'audio/wav',
            '.m4a': 'audio/m4a',
            '.aac': 'audio/aac'
        }

        for file_path in load_files(self.file_path):
            if os.path.exists(file_path):
                file_name = os.path.basename(file_path)
                file_extension = os.path.splitext(file_path)[1].lower()
                file_type = file_type_mapping.get(file_extension, 'application/octet-stream')
                files.append(('files', (file_name, open(file_path, 'rb'), file_type)))
            else:
                print(f"文件不存在: {file_path}")
        return files


    def run(self):
        try:
            files = self.generate_files_data()
            response = request(f"{Config.Host}/api/upload/files/", method='POST', headers=self.headers, files=files, data={})
            result = [i.get("signed_url") for i in response.json()["data"] if i.get("signed_url")]
            if not result:
                raise Exception("上传文件失败")
            data = {
                "files": result,
                "SpeechTexts": self.subtitle,
                "OutputConfig": {"count": self.count},
                "EditingConfig": {"speech_config": {"voice": self.voice}}
            }
            submit_response = request(f"{Config.Host}/api/ai-mix/", method='POST', headers=self.headers, data=json.dumps(data))
            submit_response.raise_for_status()
            task_id = submit_response.json()["data"]["result_url"]

            while True:
                try:
                    data = {"task_id": task_id}
                    response = request(f"{Config.Host}/api/get/ai-mix/result/", method='POST', data=json.dumps(data), headers=self.headers)
                    response.raise_for_status()
                    retv = response.json().get("data")
                    if retv and retv.get("images_list"):
                        self.result.emit(retv.get("images_list"))
                        break
                except Exception as e:
                    traceback.print_exc()

        except Exception as e:
            self.failed.emit(e)
            traceback.print_exc()